package com.kapo.egroup.controller;

import com.kapo.egroup.common.Result;
import com.kapo.egroup.entity.base.lesson.Lesson;
import com.kapo.egroup.entity.base.lesson.LessonTask;
import com.kapo.egroup.entity.base.lesson.UserLessonRecord;
import com.kapo.egroup.entity.base.recruit.Recruit;
import com.kapo.egroup.entity.base.user.User;
import com.kapo.egroup.security.domain.LoginUser;
import com.kapo.egroup.service.LessonService;
import com.kapo.egroup.service.LessonTaskService;
import com.kapo.egroup.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Title LessonController
 * @Description TODO
 * @Author 86159
 * @Date 2023-04-01 21:38
 **/
@RestController
@RestControllerAdvice
@RequestMapping("/api/lesson")
public class LessonController {
    @Autowired
    private LessonService lessonService;

    @Autowired
    private LessonTaskService lessonTaskService;

    @Autowired
    private UserService userService;

    /**
     * @descriptions 根据课程ID获取课程任务
     * @author 黄家宝
     * @date 2022/8/18 17:28
     * @return com.eintern.common.Result
     */
    @CrossOrigin
    @ResponseBody
    @GetMapping("/task")
    public Result getLessonTaskByLessonId(@RequestParam Long lessonId) throws Exception{
        List<LessonTask> lessonTaskList = lessonTaskService.getLessonTaskByLessonId(lessonId);
        System.out.println(lessonTaskList);
        return Result.ok(lessonTaskList);
    }

    /**
     * @descriptions 根据课程ID获取课程
     * @author 黄家宝
     * @date 2022/8/18 17:28
     * @return com.eintern.common.Result
     */
    @CrossOrigin
    @ResponseBody
    @GetMapping("")
    public Result getLessonById(@RequestParam Long lessonId) throws Exception{
        Lesson lesson = lessonService.getById(lessonId);
        return Result.ok(lesson);
    }

    /**
     * @descriptions 根据学号获取课程
     * @author 黄家宝
     * @date 2022/8/18 17:28
     * @return com.eintern.common.Result
     */
    @CrossOrigin
    @ResponseBody
    @GetMapping("/studentId")
    public Result getLessonByStudentId() throws Exception{
        String studentId = getCurrentUserStudentId();
        List<UserLessonRecord> lessonList = lessonService.getLessonsByStudentId(studentId);
        return Result.ok(lessonList);
    }

    private String getCurrentUserStudentId(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object user = authentication.getPrincipal();
        LoginUser loginUser = (LoginUser)user;
        Long userId = loginUser.getUserId();
        User currentUser = userService.getById(userId);
        return currentUser.getStudentId();
    }
}
